package com.springboot.base.common;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author meiguangya
 */
@ControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ServerResponse handleException(HttpServletRequest req, HttpServletResponse rep, Exception e) {
        if (e instanceof BusinessException) {
            return ServerResponse.createByErrorData(((BusinessException) e).getCommonError());
        } else if (e instanceof NoHandlerFoundException) {
            return ServerResponse.createByErrorData(new CommonError(EmBusinessError.NO_PAGE_FOUND));
        } else if (e instanceof ServletRequestBindingException) {
            return ServerResponse.createByErrorData(new CommonError(EmBusinessError.BIND_ERROR));
        } else {
            return ServerResponse.createByErrorData(new CommonError(EmBusinessError.UNKNOWN_ERROR));
        }
    }

}
